package com.dj.ms.configure;

import com.aliyun.openservices.log.Client;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.ClassPathResource;

import javax.annotation.PostConstruct;
import java.util.Objects;
import java.util.Properties;

/**
 * <br>
 * <p>
 *     阿里云log-store客户端配置
 * </p>
 *
 * <br>
 * @author ZJG
 * @version 1.0
 * @date 2021/9/28 上午9:07
 */
@Slf4j
@Configuration
@Order(Ordered.HIGHEST_PRECEDENCE-100)
public class AliYunLogClientConfiguration {

    @Value("${spring.profiles.active}")
    private String activeProfiles;

    private static String props_k = "aliyun.log.store.";
    public static String host = "";
    public static String accessId = "";
    public static String accessKey = "";
    public static String projectName = "";
    public static String logStore = "admin-operation-log";
    public static String topic = "admin-operation-log";

    private static Client aliyunLogClient;

    @PostConstruct
    public void init() {
        aliyunLogClient();
    }

    private void aliyunLogClient() {
        if (Objects.nonNull(aliyunLogClient)) {
            return;
        }
        if (StringUtils.isBlank(activeProfiles)) {
            return;
        }
        props_k = props_k.concat(activeProfiles);
        YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
        yaml.setResources(new ClassPathResource("log_store_config.yml"));
        if (Objects.isNull(yaml)) {
            return;
        }

        Properties object = yaml.getObject();

        if (object.containsKey(props_k.concat(".host"))) {
            host = object.getProperty(props_k.concat(".host"));
            accessId = object.getProperty(props_k.concat(".accessId"));
            accessKey = object.getProperty(props_k.concat(".accessKey"));
            projectName = object.getProperty(props_k.concat(".projectName"));
            logStore = object.getProperty(props_k.concat(".name"));
            topic = object.getProperty(props_k.concat(".topic"));
            aliyunLogClient = new Client(host, accessId, accessKey);
        }

    }

    public static Client aliyunLogStoreClient() {
        return aliyunLogClient;
    }





}
